//
//  CRMEditorCustomerVC.m
//  New_Runway
//
//  Created by NewLife on 2018/2/26.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CRMEditorCustomerVC.h"
#import "NRWCarInputItemView.h"
#import "NRWCarRemarkTextView.h"
#import "NRWCarChooseTableVC.h"
#import "PickCityView.h"
#import "CRMEditorCustomerModel.h"

@interface CRMEditorCustomerVC ()<UITextFieldDelegate, UITextViewDelegate, UITableViewDelegate, UITableViewDataSource, PickerCityViewDelegate, NRWCarInputItemViewDelegate>

@property (strong, nonatomic) CRMEditorCustomerModel *model;

@end

@implementation CRMEditorCustomerVC
{
    UITableView *tableView;
    NRWCarInputItemView *customNameItem;
    NRWCarInputItemView *genderChooseItem;
    NRWCarInputItemView *mobileItem;
    NRWCarInputItemView *customerFrom;
    NRWCarInputItemView *customerLevelItem;
    NRWCarInputItemView *locationItem;
    NRWCarInputItemView *budgetItem;
    NRWCarRemarkTextView *remarkTextView;
    
    NSString *_channelId;
    NSString *_levelId;
    NSString *_cityName;
    NSString *_provinceName;
    NSString *_cityId;
    NSString *_provinceId;
}

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.isAddCustomer) {
        self.navigationBarView.titleLabel.text = @"新增客户";
    } else {
        self.navigationBarView.titleLabel.text = @"编辑客户";
    }
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
    
    if (self.isAddCustomer) {
        return;
    }
    
    [self loadEdtorInfoData];
}

#pragma mark - setupUI
CGFloat itemH = 40;
- (void)setupUI {
    
    UITableViewController *tvc = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
    [self addChildViewController:tvc];
    tvc.view.frame = CGRectMake(0, self.navH, Screen_width, Screen_height - self.navH - self.BotH);
    tableView = tvc.tableView;
    
    tableView.setSeparatorStyle(UITableViewCellSeparatorStyleNone);
    tableView.delegate = self;
    tableView.dataSource = self;
    
    self.view.addSubview(tableView);
    
    [self.navigationBarView setupRightItemTitle:@"确定"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 8;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *str = [NSString stringWithFormat:@"%zd",indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:str];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (cell.contentView.subviews.count > 0) {
        return cell;
    }
    
    if (indexPath.row == 0) {
        [self addCustomerNameItemForCell:cell];
    } else if (indexPath.row == 1) {
        [self addGenderItemForCell:cell];
    } else if (indexPath.row == 2) {
        [self addMobileItemForCell:cell];
    } else if (indexPath.row == 3) {
        [self addCustomerFromItemForCell:cell];
    } else if (indexPath.row == 4) {
        [self addCustomerLevelItemForCell:cell];
    } else if (indexPath.row == 5) {
        [self addLocationItemForCell:cell];
    } else if (indexPath.row == 6) {
        [self addDudgetItemForCell:cell];
    } else if (indexPath.row == 7) {
        [self addRemarkItemForCell:cell];
    }
    
    customNameItem.tag = 0;
    genderChooseItem.tag = 1;
    mobileItem.tag = 2;
    customerFrom.tag = 3;
    customerLevelItem.tag = 4;
    locationItem.tag = 5;
    budgetItem.tag = 6;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 7) {
        return 185;
    }
    return 40;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    [self.view endEditing:YES];
}

- (void)addCustomerNameItemForCell:(UITableViewCell *)cell {
    
    customNameItem = [[NRWCarInputItemView alloc] initWithInputItemWithPlaceHolder:@"请输入客户名称" delegate:self showArrow:NO];
    NSString *customNameTitle = @"*客户名称";
    customNameItem.titleAttributedString = [customNameTitle attributedStringWithFirstTextColor:getColorFromString(@"ff0000") firstRange:NSMakeRange(0, 1) secondTextColor:getColorFromString(@"323232") secondRange:NSMakeRange(1, customNameTitle.length - 1)];
    customNameItem.titleRectOffset = -[@"*" sizeWithFont:kPingFangRegular13() andMaxSize:CGSizeMake(100, 100)].width;
    customNameItem.frame = CGRectMake(0, 0, Screen_width, itemH);
    
    cell.contentView.addSubview(customNameItem);
}

- (void)addGenderItemForCell:(UITableViewCell *)cell {
    
    genderChooseItem = [[NRWCarInputItemView alloc] initWithTwoChooseItemWithTitle1:@"男" title2:@"女"];
    genderChooseItem.chooseIndex = 0;
    genderChooseItem.titleAttributedString = [@"*性别" attributedStringWithFirstTextColor:getColorFromString(@"ff0000") firstRange:NSMakeRange(0, 1) secondTextColor:getColorFromString(@"323232") secondRange:NSMakeRange(1, @"*性别".length - 1)];
    genderChooseItem.titleRectOffset = -[@"*" sizeWithFont:kPingFangRegular13() andMaxSize:CGSizeMake(100, 100)].width;
    genderChooseItem.frame = CGRectMake(0, 0, Screen_width, itemH);
    
    cell.contentView.addSubview(genderChooseItem);
}

- (void)addMobileItemForCell:(UITableViewCell *)cell {
    
    mobileItem = [[NRWCarInputItemView alloc] initWithInputItemWithPlaceHolder:@"请输入客户手机号码" delegate:self  showArrow:NO];
    mobileItem.titleAttributedString = [@"*客户电话" attributedStringWithFirstTextColor:getColorFromString(@"ff0000") firstRange:NSMakeRange(0, 1) secondTextColor:getColorFromString(@"323232") secondRange:NSMakeRange(1, @"*客户电话".length - 1)];
    mobileItem.titleRectOffset = -[@"*" sizeWithFont:kPingFangRegular13() andMaxSize:CGSizeMake(100, 100)].width;
    mobileItem.keyboardType = UIKeyboardTypeNumberPad;
    mobileItem.delegate = self;
    mobileItem.frame = CGRectMake(0, 0, Screen_width, itemH);
    cell.contentView.addSubview(mobileItem);
    
}

- (void)addCustomerFromItemForCell:(UITableViewCell *)cell {
    
    customerFrom = [[NRWCarInputItemView alloc] initWithInputItemWithPlaceHolder:@"请选择客服来源" delegate:self showArrow:YES];
    customerFrom.frame = CGRectMake(0, 0, Screen_width, itemH);
    customerFrom.titleAttributedString = [@"*客户来源" attributedStringWithFirstTextColor:getColorFromString(@"ff0000") firstRange:NSMakeRange(0, 1) secondTextColor:getColorFromString(@"323232") secondRange:NSMakeRange(1, @"*客户来源".length - 1)];
    customerFrom.titleRectOffset = -[@"*" sizeWithFont:kPingFangRegular13() andMaxSize:CGSizeMake(100, 100)].width;
    cell.contentView.addSubview(customerFrom);
}

- (void)addCustomerLevelItemForCell:(UITableViewCell *)cell {
    
    customerLevelItem = [[NRWCarInputItemView alloc] initWithInputItemWithPlaceHolder:@"请选择客服等级" delegate:self showArrow:YES];
    customerLevelItem.frame = CGRectMake(0, 0, Screen_width, itemH);
    customerLevelItem.titleAttributedString = [@"*客户等级" attributedStringWithFirstTextColor:getColorFromString(@"ff0000") firstRange:NSMakeRange(0, 1) secondTextColor:getColorFromString(@"323232") secondRange:NSMakeRange(1, @"*客户等级".length - 1)];
    customerLevelItem.titleRectOffset = -[@"*" sizeWithFont:kPingFangRegular13() andMaxSize:CGSizeMake(100, 100)].width;
    cell.contentView.addSubview(customerLevelItem);
}

- (void)addLocationItemForCell:(UITableViewCell *)cell {
    
    locationItem = [[NRWCarInputItemView alloc] initWithInputItemWithPlaceHolder:@"请选择省市" delegate:self showArrow:YES];
    locationItem.frame = CGRectMake(0, 0, Screen_width, itemH);
    locationItem.titleAttributedString = [@"*归属地区" attributedStringWithFirstTextColor:getColorFromString(@"ff0000") firstRange:NSMakeRange(0, 1) secondTextColor:getColorFromString(@"323232") secondRange:NSMakeRange(1, @"*归属地区".length - 1)];
    locationItem.titleRectOffset = -[@"*" sizeWithFont:kPingFangRegular13() andMaxSize:CGSizeMake(100, 100)].width;
    cell.contentView.addSubview(locationItem);
}

- (void)addDudgetItemForCell:(UITableViewCell *)cell {
    
    budgetItem = [[NRWCarInputItemView alloc] initWithPriceRangeWithTextFieldDelegate:self];
    budgetItem.delegate = self;
    budgetItem.frame = CGRectMake(0, 0, Screen_width, itemH);
    budgetItem.titleAttributedString = [@"*预算区间" attributedStringWithFirstTextColor:getColorFromString(@"ff0000") firstRange:NSMakeRange(0, 1) secondTextColor:getColorFromString(@"323232") secondRange:NSMakeRange(1, @"*预算区间".length - 1)];
    budgetItem.titleRectOffset = -[@"*" sizeWithFont:kPingFangRegular13() andMaxSize:CGSizeMake(100, 100)].width;
    cell.contentView.addSubview(budgetItem);

}

- (void)addRemarkItemForCell:(UITableViewCell *)cell {

    UILabel *remarkLabel = DPLabel()
    .setFont(kPingFangRegular13())
    .setTextColor(getColorFromString(@"323232"))
    .setText(@"备注");
    
    remarkTextView = [[NRWCarRemarkTextView alloc] initWithRemarkTextView];

    cell.contentView.addSubview(remarkLabel).addSubview(remarkTextView);

    [remarkLabel sizeToFit];
    remarkLabel.frame = CGRectMake(16, 11, remarkLabel.width, remarkLabel.height);
    remarkTextView.frame = CGRectMake(16, remarkLabel.bottom + 11, Screen_width - 32, 140);
}

#pragma mark - privateMethod
- (void)rightItemClick {
    
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    
    if (isEmptyOrNilString(customNameItem.inputText)) {
        [SVProgressHUD showErrorWithStatus:@"客户名称不能为空" dismissDelay:1];
        return;
    } else {
        [dictM setObject:customNameItem.inputText forKey:@"customerName"];
    }
    
    if (genderChooseItem.chooseIndex == 0) {
        [dictM setObject:@"1" forKey:@"customerGender"];
    } else if (genderChooseItem.chooseIndex == 1) {
        [dictM setObject:@"2" forKey:@"customerGender"];
    } else if (genderChooseItem.chooseIndex == 2) {
        [SVProgressHUD showErrorWithStatus:@"客户性别不能为空" dismissDelay:1];
        return;
    }
    
    if (isEmptyOrNilString(mobileItem.inputText)) {
        [SVProgressHUD showErrorWithStatus:@"客户电话不能为空" dismissDelay:1];
        return;
    } else if (mobileItem.inputText.length != 11) {
        [SVProgressHUD showErrorWithStatus:@"请输入11位有效手机号码" dismissDelay:1];
    } else {
        [dictM setObject:mobileItem.inputText forKey:@"customerPhone"];
    }
    
    if (isEmptyOrNilString(_channelId) || isEmptyOrNilString(customerFrom.inputText)) {
        [SVProgressHUD showErrorWithStatus:@"客户来源不能为空" dismissDelay:1];
        return;
    } else {
        [dictM setObject:_channelId forKey:@"channelId"];
        [dictM setObject:customerFrom.inputText forKey:@"channelName"];
    }
    
    if (isEmptyOrNilString(_levelId) || isEmptyOrNilString(customerLevelItem.inputText)) {
        [SVProgressHUD showErrorWithStatus:@"客户等级不能为空" dismissDelay:1];
        return;
    } else {
        [dictM setObject:_levelId forKey:@"levelId"];
        [dictM setObject:customerLevelItem.inputText forKey:@"levelTxt"];
    }
    
    if (isEmptyOrNilString(_cityId) ||
        isEmptyOrNilString(_cityName) ||
        isEmptyOrNilString(_provinceId) ||
        isEmptyOrNilString(_provinceName)) {
        [SVProgressHUD showErrorWithStatus:@"归属地区不能为空" dismissDelay:1];
        return;
    } else {
        [dictM setObject:_provinceId forKey:@"provinceId"];
        [dictM setObject:_provinceName forKey:@"provinceName"];
        [dictM setObject:_cityId forKey:@"cityId"];
        [dictM setObject:_cityName forKey:@"cityName"];
    }
    
    if (!isEmptyOrNilString(self.model.result.lastObject.customerId)) {
        [dictM setObject:self.model.result.lastObject.customerId forKey:@"customerId"];
    }
    
    if (budgetItem.minPrice >= budgetItem.maxPrice) {
        [SVProgressHUD showErrorWithStatus:@"请输入有效价格区间" dismissDelay:1];
        return;
    } else {
        [dictM setObject:[NSString stringWithFormat:@"%.2f",budgetItem.minPrice] forKey:@"customerBudgetMin"];
        [dictM setObject:[NSString stringWithFormat:@"%.2f",budgetItem.maxPrice] forKey:@"customerBudgetMax"];
    }
    
    if (!isEmptyOrNilString(remarkTextView.text)) {
        [dictM setObject:remarkTextView.text forKey:@"customerRemark"];
    }
    
    if (!self.isAddCustomer) {
        if (isEmptyOrNilString(self.customerShopId)) {
            [SVProgressHUD showErrorWithStatus:@"customerShopId不能为空" dismissDelay:1];
            return;
        } else {
            [dictM setObject:self.customerShopId forKey:@"customerShopId"];
        }
    }
    
    if (isEmptyOrNilString(self.model.result.lastObject.marketId)) {
        [dictM setObject:[NRWCarUser sharedUser].marketId forKey:@"marketId"];
    } else {
        [dictM setObject:self.model.result.lastObject.marketId forKey:@"marketId"];
    }
    
    if (isEmptyOrNilString([NRWCarUser sharedUser].shopId)) {
        [SVProgressHUD showErrorWithStatus:@"shopId不能为空" dismissDelay:1];
        return;
    } else {
        [dictM setObject:[NRWCarUser sharedUser].shopId forKey:@"shopId"];
    }
    
    if (self.isAddCustomer) {
        [self addCustomerInfoWithParams:dictM.copy];
    } else {
        [self updataCustomerInfoWithParams:dictM.copy];
    }
}

- (void)updataCustomerInfoWithParams:(NSDictionary *)params {
    
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@", CRMContextApi, updateCustomerInfo] refreshRequest:NO cache:NO params:params.copy progressBlock:nil successBlock:^(id response) {
        [SVProgressHUD dismiss];
        if ([response[@"code"] integerValue] == 1) {
            
            [SVProgressHUD showSuccessWithStatus:@"修改成功" dismissDelay:1 didDismiss:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        } else {
            [SVProgressHUD showErrorWithStatus:response[@"msg"] dismissDelay:1];
        }
        
    } failBlock:^(NSError *error) {
        [SVProgressHUD dismiss];
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

    }];
}

- (void)addCustomerInfoWithParams:(NSDictionary *)params {
    
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@", CRMContextApi, addCustomerInfo] refreshRequest:NO cache:NO params:params.copy progressBlock:nil successBlock:^(id response) {
        [SVProgressHUD dismiss];
        if ([response[@"code"] integerValue] == 1) {
            
            [SVProgressHUD showSuccessWithStatus:@"新增成功" dismissDelay:1 didDismiss:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        } else {
            [SVProgressHUD showErrorWithStatus:response[@"msg"] dismissDelay:1];
        }
        
    } failBlock:^(NSError *error) {
        [SVProgressHUD dismiss];
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

    }];
}

- (void)loadEdtorInfoData {
    
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    
    if (isEmptyOrNilString(self.customerShopId)) {
        [SVProgressHUD showErrorWithStatus:@"customerShopId不能为空" dismissDelay:1];
        return;
    } else {
        [dictM setObject:self.customerShopId forKey:@"customerShopId"];
    }
    
    if (!isEmptyOrNilString([NRWCarUser sharedUser].shopId)) {
        [dictM setObject:[NRWCarUser sharedUser].shopId forKey:@"shopId"];
    }
    [SVProgressHUD show];
    [YQNetworking getWithUrl:[NSString stringWithFormat:@"%@%@", CRMContextApi, getCustomerInfo] refreshRequest:NO cache:NO params:dictM.copy progressBlock:nil successBlock:^(id response) {
        [SVProgressHUD dismiss];
        self.model = [CRMEditorCustomerModel mj_objectWithKeyValues:response];
        
        if (self.model.code == 1) {
            
            [self setupDataToList];
        } else {
            
            [SVProgressHUD showErrorWithStatus:self.model.msg dismissDelay:1];
        }
        
    } failBlock:^(NSError *error) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.localizedDescription dismissDelay:1];
    }];
}

- (void)setupDataToList {
    
    CRMEditorCustomerResultModel *resultModel = self.model.result.lastObject;
    
    if (!isEmptyOrNilString(resultModel.customer.customerName)) {
        customNameItem.inputText = resultModel.customer.customerName;
    }
    
    if (resultModel.customer.customerGender == 1) {
        genderChooseItem.chooseIndex = 0;
    } else if (resultModel.customer.customerGender == 2) {
        genderChooseItem.chooseIndex = 1;
    }
    
    if (!isEmptyOrNilString(resultModel.customer.customerPhone)) {
        mobileItem.inputText = resultModel.customer.customerPhone;
    }
    
    if (!isEmptyOrNilString(resultModel.channelName)) {
        customerFrom.inputText = resultModel.channelName;
    }
    
    if (!isEmptyOrNilString(resultModel.levelTxt)) {
        customerLevelItem.inputText = resultModel.levelTxt;
    }
    
    if (isEmptyOrNilString(resultModel.customer.provinceName)) {
        if (isEmptyOrNilString(resultModel.customer.cityName)) {
            locationItem.inputText = @"";
        } else {
            locationItem.inputText = resultModel.customer.cityName;
        }
    } else {
        if (isEmptyOrNilString(resultModel.customer.cityName)) {
            locationItem.inputText = resultModel.customer.provinceName;
        } else {
            locationItem.inputText = [NSString stringWithFormat:@"%@ %@",resultModel.customer.provinceName, resultModel.customer.cityName];
        }
    }
    
    budgetItem.minPrice = resultModel.customerBudgetMin;
    budgetItem.maxPrice = resultModel.customerBudgetMax;
    if (!isEmptyOrNilString(resultModel.customerRemark)) {
        remarkTextView.text = resultModel.customerRemark;
    }
    
    _provinceId = resultModel.customer.provinceId;
    _cityId = resultModel.customer.cityId;
    _levelId = resultModel.levelId;
    _channelId = resultModel.channelId;
    _provinceName = resultModel.customer.provinceName;
    _cityName = resultModel.customer.cityName;
}

#pragma mark - publicMethod

#pragma mark - DelegateMethod
- (void)inputItemView:(NRWCarInputItemView *)view textFieldTextDidChange:(UITextField *)sender {
    
    if (view == mobileItem) {
        if (sender.text.length > 11) {
            sender.text = [sender.text substringToIndex:11];
        }
    }
    
    if (view == budgetItem) {
        sender.text = [sender.text returnRealPrice];
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    [self.view endEditing:YES];
    
    if (textField.tag == 3) {//客户来源
        
        NRWCarChooseTableVC *vc = [[NRWCarChooseTableVC alloc] init];
        vc.chooseType = NRWCarChooseTableVCTypeChannel;
        [self.navigationController pushViewController:vc animated:YES];
        
        vc.chooseCompleted = ^(NSString *itemId, NSString *itemName) {
          
            _channelId = itemId;
            customerFrom.inputText = itemName;
        };
        return NO;
    } else if (textField.tag == 4) {//客户等级
        
        NRWCarChooseTableVC *vc = [[NRWCarChooseTableVC alloc] init];
        vc.chooseType = NRWCarChooseTableVCTypeLevel;
        [self.navigationController pushViewController:vc animated:YES];
        
        vc.chooseCompleted = ^(NSString *itemId, NSString *itemName) {
            
            _levelId = itemId;
            customerLevelItem.inputText = itemName;
        };
        return NO;
    } else if (textField.tag == 5) {//归属地区
        
        PickCityView *pickCity = [[PickCityView alloc] init];
        pickCity.delegate = self;
        pickCity.pickerViewHeight = 300;
        [pickCity show];
        return NO;
    } else if (textField.tag == 6) {//预算区间
        
        return NO;
    }
    return YES;
}

#pragma mark PickCityView
- (void)pickerArea:(PickCityView *)pickerArea selectProvince:(NSString *)province selectCity:(NSString *)city {
    
    locationItem.inputText = [NSString stringWithFormat:@"%@ %@",province, city];
    _cityName = city;
    _provinceName = province;
}

- (void)pickerArea:(PickCityView *)pickerArea selectProvinceId:(NSString *)provinceId selectCityId:(NSString *)cityId {
    
    _provinceId = provinceId;
    _cityId = cityId;
}

#pragma mark - touchEventAction

#pragma mark - setter

#pragma mark - getter


@end
